package com.zy.mobile.message.push.netty.heartbeat;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import com.zy.mobile.message.push.netty.heartbeat.protobuf.MessageProto;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;

public class HeartBeatClient {
	
	private ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
	
	public void connect(final int port,final String host)throws Exception{
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioSocketChannel.class)
				.option(ChannelOption.TCP_NODELAY,true)
//				.option(ChannelOption.SO_KEEPALIVE,true)
				.handler(new ChannelInitializer<SocketChannel>() {
					@Override
					protected void initChannel(SocketChannel ch)
							throws Exception {
						// TODO Auto-generated method stub
						ch.pipeline().addLast(new ProtobufVarint32FrameDecoder());
						ch.pipeline().addLast(new ProtobufDecoder(MessageProto.Message.getDefaultInstance()));
						ch.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
						ch.pipeline().addLast(new ProtobufEncoder());
						ch.pipeline().addLast(new HeartBeatClientHandler(2));
					}
			});
			
			//发起异步连接操作
			ChannelFuture f = b.connect(host,port).sync();
			//等待客户端链路关闭
			f.channel().closeFuture().sync();
			
		} catch (Exception e) {
			// TODO: handle exception
		} finally{
//			group.shutdownGracefully();
			System.out.println("断线重连");
			executor.execute(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					try {
						TimeUnit.SECONDS.sleep(5);
						try {
							connect(port, host);
						} catch (Exception e2) {
							// TODO: handle exception
							e2.printStackTrace();
						}
					} catch (Exception e2) {
						// TODO: handle exception
						e2.printStackTrace();
					}				
				}
			});
		}
	}
	
	public static void main(String[] args) throws Exception {
		int port = 8088;
		if(args != null && args.length>0){
			try {
				port = Integer.valueOf(args[0]);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		new HeartBeatClient().connect(port,"10.100.0.177");
	}
}
